<?php
/**
 * 产品
 */
namespace app\usercp\controller;

use app\usercp\exception\UsercpException;
use think\Request;

class Site extends Usercp
{
    public function initialize() {
        parent::initialize();
        $this->service = model('site/Site', 'service');
    }

    /**
     * 列表
     */
    public function index(Request $request)
    {
        $lists = $this->service->where('custom_id|create_custom_id','=',$this->custom->current_id)->find();
        if(empty($lists)){
            return $this->fetch('none');
        }
        return $this->fetch('index');
    }
    /**
     * [lists 列表]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function lists(Request $request)
    {
        if ($request->isAjax()){
            $maps = [];
            $maps['name'] = $request->get('name','');
            $maps['custom_ids'] = $this->custom->current_id;
            $create_time = $request->get('create_time','');
            $deadline = $request->get('deadline','');
            if(!empty($create_time)){
                $maps['create_time'] = explode(' - ', $create_time);
            }
            if(!empty($deadline)){
                $maps['deadline'] = explode(' - ', $deadline);
            }

            $limit = $request->get('limit');
            $page = $request->get('page',false);
            $order = $request->get('order','create_time desc');
            $field = $request->get('field',true);
            $relations = $request->get('relations',[]);
            $attrs = $request->get('attrs',[]);
            $lists = $this->service->lists($maps, $order,$page,$limit, $field , $relations , $attrs);
            if ($lists->isEmpty()){
                return $this->result('',0,'暂无数据');
            }
            foreach ($lists as $key => $list) {
                $lists[$key]['custom_name'] = $list->custom_info->username;
            }
            return $this->result($lists,200);
        }
        return $this->fetch('manage');
    }
    /**
     * [setting 站点设置]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function setting(Request $request)
    {
        if ($request->isAjax()){
            $info = [
                'id' => $request->post('id'),
                'name' => $request->post('name'),
                'token' => $request->post('token'),
                //'desc' => $request->post('desc'),
                'custom_id' => $this->custom->current_id,
                //'logo' => $request->post('logo'),
                //'phone' => $request->post('phone')
            ];
            $validate = $this->validate($info, 'app\site\validate\Site.edit');
            if (true !== $validate) {
                return $this->result('',0,$validate);
            }
            $result = $this->service->edit($info,$this->custom->current_id);
            if($result === false){
                return $this->result($result,0,$this->service->getError());
            }
            $setting = [
                'site_id' => $request->post('id'),
                'custom_id' => $this->custom->current_id,
                'appid' => $request->post('appid'),
                'app_key' => $request->post('app_key'),
                'app_secret' => $request->post('app_secret'),
                'type' => $request->post('type','baidu')
            ];
            $validate = $this->validate($setting, 'app\site\validate\SiteSetting.setting');
            if (true !== $validate) {
                return $this->result('',0,$validate);
            }
            $setting_result = $this->service->setting($setting['site_id'],$setting['custom_id'],$setting['appid'],$setting['app_key'],$setting['app_secret'],$setting['type']);
            if($setting_result === false){
                return $this->result($setting_result,0,$this->service->getError());
            }
            return $this->result($result,200);
        }
        return $this->fetch('setting');
    }
    /**
     * [new description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function new(Request $request){
        if ($request->isAjax()){
            $info = [
                'name' => $request->post('name'),
                'desc' => $request->post('desc',''),
                'custom_id' => $request->post('custom_id'),
                'type' => $request->post('type'),
                'number' => $request->post('number'),
                'app_type' => $request->post('app_type'),
                'appid' => $request->post('appid',''),
                'app_key' => $request->post('app_key',''),
                'app_secret' => $request->post('app_secret',''),
                'style_id' => $request->post('style_id',1)
            ];
            $validate = $this->validate($info, 'app\site\validate\Site.create');
            if (true !== $validate) {
                return $this->result('',0,$validate);
            }
            $validate = $this->validate($info, 'app\site\validate\SiteSetting.create');
            if (true !== $validate) {
                return $this->result('',0,$validate);
            }
            $result = $this->service->create($info['name'],$info['type'],$info['number'],$info['app_type'],$info['custom_id'],$this->custom->current_id,$info['desc'],$info['appid'],$info['app_key'],$info['app_secret'],$info['style_id']);
            if($result === false){
                return $this->result($result,0,$this->service->getError());
            }
            return $this->result($result,200);
        }
        $templates = model('site/SiteTemplateStyle')->select();
        $this->assign('templates',$templates);
        return $this->fetch('new');
    }
    /**
     * 添加文章页面
     */
    public function create(Request $request)
    {
        if ($request->isAjax()){
            $info = [
                'name' => $request->post('name'),
                'desc' => $request->post('desc',''),
                'custom_id' => $request->post('custom_id'),
                'type' => $request->post('type'),
                'number' => $request->post('number'),
                'app_type' => $request->post('app_type'),
            ];
            $validate = $this->validate($info, 'app\site\validate\Site.create');
            if (true !== $validate) {
                return $this->result('',0,$validate);
            }
            $setting = [
                'appid' => $request->post('appid',''),
                'app_key' => $request->post('app_key',''),
                'app_secret' => $request->post('app_secret',''),
            ];
            $result = $this->service->create($info['name'],$info['type'],$info['number'],$info['app_type'],$info['custom_id'],$this->custom->current_id,$info['desc'],$setting['appid'],$setting['app_key'],$setting['app_secret']);
            if($result === false){
                return $this->result($result,0,$this->service->getError());
            }
            return $this->result($result,200);
        }
        return $this->fetch('create');
    }
    /**
     * [custom_lists description]
     * @return [type] [description]
     */
    public function custom_lists(Request $request)
    {
        if($request->isAjax()){
            $maps['status'] = 1;
            $maps['parent_current_id|current_id'] = $this->custom['current_id'];
            $list = model('custom/Custom','service')->where($maps)->select();
            if($list === false){
                return $this->result($result,0,$this->service->getError());
            }
            return $this->result($list,200);
        }
        return ;
    }
    /**
     * [custom_lists description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function get_token(Request $request)
    {
        if($request->isAjax()){
            $result = $this->service->get_token($request->get('site_id'));
            if($result === false){
                return $this->result($result,0,$this->service->getError());
            }
            return $this->result($result,200);
        }
        return ;
    }
    /**
     * [renew description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function renew(Request $request)
    {
        if ($request->isAjax()){
            $site_id = $request->post('id','');
            $type = $request->post('type','');
            $number = $request->post('number','');
            $result = $this->service->renew($site_id,$this->custom->current_id,$type,$number);
            if($result === false){
                return $this->result($result,0,$this->service->getError());
            }
            return $this->result($result,200);
        }
        return $this->fetch('renew');
    }
    /**
     * 详情
     */
    public function detail(Request $request)
    {
        if ($request->isAjax()){
            $result = $this->service->detail($this->request->get('id'),$this->custom->current_id);
            if($result === false){
                return $this->result($result,0,$this->service->getError());
            }
            return $this->result($result,200);
        }
    }

    /**
     * 编辑
     */
    public function edit(Request $request )
    {
        if ($request->isAjax()){
            $info = [
                'id' => $request->post('id'),
                'name' => $request->post('name'),
                'desc' => $request->post('desc'),
                'custom_id' => $request->post('custom_id'),
                'logo' => $request->post('logo'),
                'phone' => $request->post('phone')
            ];
            $validate = $this->validate($info, 'app\site\validate\Site.edit');
            if (true !== $validate) {
                return $this->result('',0,$validate);
            }
            $result = $this->service->edit($info,$this->custom->current_id);
            if($result === false){
                return $this->result($result,0,$this->service->getError());
            }
            return $this->result($result,200);
        }
        return $this->fetch('edit');
    }
  
    /**
     * [get_package 获取下载链接]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function get_package(Request $request){
        $site_id = $request->get('site_id','');
        $type = $request->get('type','');
        $result = $this->service->valid_site($site_id,$this->custom->current_id,$type);
        if($result === false){
            return $this->result($result,0,$this->service->getError());
        }
        $url = $request->domain();
        $url .= '/usercp/site/download?site_id='.$site_id.'&type='.$type;

        return $this->result($url,200);
    }
    /**
     * [download description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function download(Request $request){
        $site_id = $request->get('site_id','');
        $type = $request->get('type','');
        $file = $this->service->download($site_id,$this->custom->current_id,$type);
        if($file === false){
            return $this->result($file,0,$this->service->getError());
        }
        $fp = fopen($file['filepath'],"r"); 
        $file_size = filesize($file['filepath']);//获取文件的字节
        //下载文件需要用到的头 
        Header("Content-type: application/octet-stream"); 
        Header("Accept-Ranges: bytes"); 
        Header("Accept-Length:".$file_size);
        Header("Content-Disposition: attachment; filename=".$file['downname']); 
        $buffer = 1024; //设置一次读取的字节数，每读取一次，就输出数据（即返回给浏览器） 
        $file_count = 0; //读取的总字节数 
        //向浏览器返回数据 如果下载完成就停止输出，如果未下载完成就一直在输出。根据文件的字节大小判断是否下载完成
        while(!feof($fp) && $file_count < $file_size){  
            $file_con = fread($fp,$buffer);  
            $file_count += $buffer;  
            echo $file_con;  
        } 
        fclose($fp); 
        //下载完成后删除压缩包，临时文件夹 
        if($file_count >= $file_size) { 
            unlink($file['filepath']); 
        }
    }
    /**
     * [get_fee description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function get_renew_fee(Request $request){
        $type = $request->get('type','');
        $number = $request->get('number',0);
        $result = $this->service->get_renew_fee($type,$number,$this->custom->current_id);
        if($result === false){
            return $this->result($result,0,$this->service->getError());
        }
        return $this->result(['balance' => $this->custom->balance,'fee' => $result],200);
    }
    /**
     * [get_fee description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function get_create_fee(Request $request){
        $type = $request->get('type','');
        $number = $request->get('number',0);
        $result = $this->service->get_create_fee($type,$number,$this->custom->current_id);
        if($result === false){
            return $this->result($result,0,$this->service->getError());
        }
        return $this->result(['balance' => $this->custom->balance,'fee' => $result],200);
    }
    /**
     * [template description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function template(Request $request){
        if ($request->isAjax()){
            $site_id = $request->post('site_id','');
            $type_id = $request->post('type_id',0);
            $type = $request->post('type','baidu');
            $result = $this->service->template($site_id,$type_id,$type,$this->custom->current_id);
            if($result === false){
                return $this->result($result,0,$this->service->getError());
            }
            return $this->result($result,200);
        }
        $site_id = $request->get('site_id','');
        $site_template = model('site/SiteSetting')->where('site_id','=',$site_id)->select()->toArray();
        $site_template = \fast\ArrayHelper::reform_arr($site_template,'type');
        $templates = model('site/SiteTemplateStyle')->select();
        $this->assign('templates',$templates)->assign('site_template',$site_template);
        return $this->fetch('template');
    }
}